package com.bj.zspace.cat.controller;

import com.dianping.cat.Cat;
import com.dianping.cat.message.Message;
import com.dianping.cat.message.Transaction;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @Author:liuwenqing
 * @Date:2024/12/4 20:43
 * @Description:
 **/
@RestController
public class TaggedTransactionTest {

    @GetMapping("/tag1")
    public String tag1() {
        Cat.newTaggedTransaction("tag1", "tag1_name", "position");

        Transaction transaction = Cat.newTransaction("tag1_child", "tag1_child_name");
        // 需要在Transaction之间bind操作
        Cat.getManager().bind("position", "position bind");
        transaction.setStatus(Message.SUCCESS);
        transaction.complete();
        return "ok";
    }

    @GetMapping("/tag2")
    public String tag2() throws InterruptedException {

        Transaction t = Cat.newTransaction("TaggedRoot", "Root");
        Cat.newTaggedTransaction("TaggedChild", "Child1", "Tag1");
        new TaggedThread("TaggedThread", 1, "Tag1").start();
        new TaggedThread("TaggedThread1", 1, "Tag1").start();
        TimeUnit.SECONDS.sleep(1);
        t.setStatus(Message.SUCCESS);
        t.complete();

        new TaggedThread("TaggedThread2", 1, "Tag1").start();
        return "ok";
    }

    class TaggedThread extends Thread {

        private String type;

        private long sleep;

        private String tag;

        public TaggedThread(String type, long sleep, String tag) {
            this.type = type;
            this.sleep = sleep;
            this.tag = tag;
        }

        @Override
        public void run() {

            Transaction transaction = Cat.newTransaction(type, tag);
            try {
                TimeUnit.SECONDS.sleep(sleep);
                transaction.setStatus(Message.SUCCESS);
                Cat.getManager().bind(tag, "child Tagged Thread");
            } catch (Exception e) {
                transaction.setStatus(e);
            } finally {
                transaction.complete();
            }

        }

    }

}
